package com.mallbook.controller.servlet.front;

import com.alibaba.fastjson.JSON;
import com.mallbook.model.exception.ServiceException;
import com.mallbook.model.pojo.Buys;
import com.mallbook.model.pojo.OrdersDetails;
import com.mallbook.model.pojo.User;
import com.mallbook.model.service.CartService;
import com.mallbook.model.service.CategoryService;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-07-13
 */
@WebServlet("/cart")
public class CartServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(CartServlet.class);
    private CartService cartService = new CartService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        String opr = req.getParameter("opr");
        System.out.println(opr);
        switch (opr) {
            case "add":
                doAdd(req, resp);
                break;
            case "list":
                doList(req, resp);
                break;
            case "getList":
                doGetList(req, resp);
                break;
            case "del":
                doDel(req, resp);
                break;
            case "changeNum":
                doChangeNum(req, resp);
                break;
            case "delAll":
                doDelAll(req, resp);
                break;

        }
    }

    private void doDelAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] gids = req.getParameterValues("gids");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("USER");
        PrintWriter writer = resp.getWriter();
        JSONObject jsonObject = new JSONObject();

        // 转为整形数组
        int[] gidsInt = Arrays.stream(gids).mapToInt(Integer::parseInt).toArray();
        List<Integer> gidsIntList = new ArrayList<>();
        for (int value : gidsInt) {
            logger.info("删除的商品ID：gid：{}", value);
            gidsIntList.add(value);
        }
        logger.info("用户{}开始批量删除购物车数据", user.getUsername());
        try {
            cartService.delCartMore(user.getId(), gidsIntList);
            jsonObject.put("msg", "ok");
            writer.print(jsonObject);
            writer.close();
            logger.info("用户{}批量删除购物车商品,成功！！", user.getUsername());
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonObject.put("msg", "系统维护中");
            writer.print(jsonObject);
            writer.close();
            logger.error("用户{}批量删除购物车数据失败，数据操作异常", user.getUsername());
        }
    }

    private void doChangeNum(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String num = req.getParameter("num");
        String gid = req.getParameter("gid");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("USER");
        PrintWriter writer = resp.getWriter();
        JSONObject jsonObject = new JSONObject();
        logger.info("用户{}修改购物车商品{}数量为：{}", user.getUsername(), gid, num);
        try {
            logger.info("num：{}", Integer.parseInt(num));
            logger.info("gid：{}", Integer.parseInt(gid));
            logger.info("uid：{}", user.getId());
            cartService.updateCartByUidAndGid(Integer.parseInt(num), Integer.parseInt(gid), user.getId());
            jsonObject.put("msg", "ok");
            writer.print(jsonObject);
            writer.close();
            logger.info("用户{}修改购物车商品{}数量为：{},成功！！", user.getUsername(), gid, num);
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonObject.put("msg", "系统维护中");
            writer.print(jsonObject);
            writer.close();
            logger.error("用户{}修改购物车数据失败，数据操作异常", user.getUsername());
        }
    }

    private void doDel(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String gid = req.getParameter("gid");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("USER");
        PrintWriter writer = resp.getWriter();
        JSONObject jsonObject = new JSONObject();
        logger.info("用户{}删除购物车数据", user.getUsername());
        try {
            if (gid != null && !gid.isEmpty() && user.getId() != null) {
                cartService.delCart(user.getId(), Integer.parseInt(gid));
                jsonObject.put("msg", "ok");
                writer.print(jsonObject);
                writer.close();
                logger.error("用户{}删除购物车数据，成功！", user.getUsername());
            }
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonObject.put("msg", "系统维护中");
            writer.print(jsonObject);
            writer.close();
            logger.error("用户{}删除购物车数据，数据操作异常", user.getUsername());
        }

    }

    private void doGetList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("USER");
        logger.info("用户  {}  开始请求购物车数据", user.getUsername());
        List<Buys> buysList = cartService.getCartByUid(user.getId());
        String jsonObject = JSON.toJSONString(buysList);
        PrintWriter writer = resp.getWriter();
        writer.write(jsonObject);
        writer.close();
    }

    private void doList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.getRequestDispatcher("/WEB-INF/front/cart.jsp").forward(req, resp);
    }

    private void doAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String uid = req.getParameter("uid");
        String gid = req.getParameter("gid");
        String nums = req.getParameter("gNums");
        PrintWriter writer = resp.getWriter();
        logger.info("用户{}开始添加购物车", uid);
        JSONObject jsonObject = new JSONObject();
        if (uid == null || uid.isEmpty()) {
            logger.info("uid为空");
            jsonObject.put("msg", "uid为空");
            writer.print(jsonObject);
            writer.close();
            return;
        }
        if (gid == null || gid.isEmpty()) {
            logger.info("gid为空");
            jsonObject.put("msg", "gid为空");
            writer.print(jsonObject);
            writer.close();
            return;
        }
        if (nums == null || nums.isEmpty()) {
            logger.info("nums为空");
            jsonObject.put("msg", "nums为空");
            writer.print(jsonObject);
            writer.close();
            return;
        }
        try {
            cartService.addCart(Integer.parseInt(uid), Integer.parseInt(gid), Integer.parseInt(nums));
            int allGoods = cartService.getGoodsNumByuId(Integer.parseInt(uid));
            jsonObject.put("msg", "ok");
            jsonObject.put("num", allGoods);
            writer.print(jsonObject);
            writer.close();
            logger.info("用户{}添加购物车成功", uid);
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonObject.put("msg", "系统维护中");
            writer.print(jsonObject);
            writer.close();
            logger.error("用户{}添加购物车，数据操作异常", uid);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
